package com.sfang.common.extension;

import com.alibaba.fastjson.JSON;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/*@Component
@Aspect*/
public class CommonInterceptor {
    private static Logger LOGGER = LoggerFactory.getLogger(CommonInterceptor.class);

    /**
     * 定义一个切入点.
     * 解释下：
     * <p>
     * ~ 第一个 * 代表任意修饰符及任意返回值.
     * ~ 第二个 * 定义在web包或者子包
     * ~ 第三个 * 任意方法
     * ~ .. 匹配任意数量的参数.
     */
    @Pointcut("execution(* com.aurora..*.*(..))")
    public void logPointcut() {
    }

    @org.aspectj.lang.annotation.Around("logPointcut()")
    public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {
        long start = System.currentTimeMillis();
        try {
            Object result = joinPoint.proceed();
            long end = System.currentTimeMillis();

            long elapse = end - start;

            if (elapse < 1000) {
                /*LOGGER.info(String.format("%s elapse:%sms",
                        assemblyClassAndMethod(joinPoint),
                        elapse));*/
            } else
                try {
                    LOGGER.warn(String.format("%s elapse greater than threshold:%sms paras:%s",
                            assemblyClassAndMethod(joinPoint),
                            elapse,
                            JSON.toJSONString(joinPoint.getArgs())));
                } catch (Exception e) {
                    LOGGER.warn(String.format("%s elapse greater than threshold:%sms paras:%s",
                            assemblyClassAndMethod(joinPoint),
                            elapse,
                            null));
                }
            return result;

        } catch (Throwable e) {
            throw e;
        }
    }

    private String assemblyClassAndMethod(ProceedingJoinPoint joinPoint) {
        return joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName();
    }

}
